import { dateFormat, pick } from 'miniprogram-licia'
import wxValidate from 'wechat-validate'

Page({
  behaviors: [wxValidate],
  data: {
    minDate: Date.now(),
    maxDate: Date.now() + 1000 * 60 * 60 * 24 * 2,

    houseId: '',
    houseName: '',

    name: '',
    gender: 1, // 1-男, 0-女
    mobile: '',
    visitDate: '',

    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [
      { name: '北京西三旗花园1号楼 101' },
      { name: '北京东村家园3号楼 302' },
      { name: '北京育新花园3号楼 703' },
      { name: '北京天通苑北苑8号楼 403' },
    ],
  },

  rules: {
    houseId: [{ required: true, message: '请选择到访的房屋!' }],
    name: [
      { required: true, message: '访客姓名不能为空!' },
      { pattern: /[\u4e00-\u9fa5]{2,5}/, message: '访客姓名只能为中文!' },
    ],
    mobile: [
      { required: true, message: '访客手机号不能为空!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    visitDate: [{ required: true, message: '请选择到访的日期!' }],
  },

  setVisitDate(e) {
    this.setData({
      visitDate: dateFormat(new Date(e.detail), 'yyyy-mm-dd'),
      dateLayerVisible: false,
    })
  },

  setHouseData(e) {
    const { id, name } = e.detail
    this.setData({
      houseId: id,
      houseName: name,
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async submit() {
    if (this.validate()) {
      const formData = pick(this.data, ['houseId', 'name', 'gender', 'mobile', 'visitDate'])
      const res = await wx.http({
        method: 'post',
        url: '/visitor',
        data: formData,
      })
      wx.redirectTo({
        url: '/visitor_pkg/pages/passport/index?id=' + res.data.id,
      })
    }
  },

  async onLoad() {
    const res = await wx.http({ url: '/house' })
    this.setData({ houseList: res.data })
  },
})
